"""
统一的WVP集成API端点
Unified WVP Integration API Endpoints

基于原始wvp_service.py，提供从Java后端获取真实WVP数据的API
"""
import logging
from datetime import datetime
from typing import List, Dict, Any, Optional
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel

from services.wvp_service_unified import get_unified_wvp_service
from api.services import CameraService
from database.simple_db import get_database_manager

logger = logging.getLogger(__name__)
router = APIRouter()

# 获取统一WVP服务
wvp_service = get_unified_wvp_service()


class DeviceRegister(BaseModel):
    """设备注册请求模型"""
    device_id: str
    device_name: str
    device_type: str = "camera"
    manufacturer: Optional[str] = None
    model: Optional[str] = None
    ip_address: Optional[str] = None
    port: int = 5060
    username: Optional[str] = None
    password: Optional[str] = None


@router.get("/test-connection")
async def test_wvp_connection():
    """测试Java后端WVP连接"""
    try:
        result = await wvp_service.test_wvp_connection()
        
        if result["success"]:
            return {
                "success": True,
                "message": "Java后端WVP连接成功",
                "server_url": result["data"]["server_url"],
                "total_devices": result["data"]["total_devices"],
                "connection_time": result["data"]["connection_time"]
            }
        else:
            raise HTTPException(
                status_code=503,
                detail=result["message"]
            )
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"测试WVP连接失败: {e}")
        raise HTTPException(status_code=500, detail=f"测试连接失败: {str(e)}")


@router.get("/cameras")
async def get_wvp_cameras(
    page: int = Query(1, ge=1, description="页码"),
    count: int = Query(50, ge=1, le=1000, description="每页数量"),
    use_cache: bool = Query(True, description="是否使用缓存")
):
    """获取WVP摄像头列表（从Java后端获取真实数据）"""
    try:
        result = await wvp_service.get_camera_list(page=page, count=count, use_cache=use_cache)
        
        if result["success"]:
            return {
                "success": True,
                "data": result["data"],
                "message": result["message"]
            }
        else:
            raise HTTPException(
                status_code=404,
                detail=result["message"]
            )
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取WVP摄像头列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取摄像头列表失败: {str(e)}")


@router.get("/cameras/{device_id}/{channel_id}/play-url")
async def get_camera_play_url(device_id: str, channel_id: str):
    """获取摄像头播放URL（从Java后端WVP获取）"""
    try:
        result = await wvp_service.get_camera_play_url(device_id, channel_id)
        
        if result["success"]:
            return {
                "success": True,
                "data": result["data"],
                "message": result["message"]
            }
        else:
            raise HTTPException(
                status_code=404,
                detail=result["message"]
            )
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取播放URL失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取播放URL失败: {str(e)}")


@router.post("/cameras/{device_id}/{channel_id}/stop-play")
async def stop_camera_play(device_id: str, channel_id: str):
    """停止摄像头播放（通过Java后端WVP）"""
    try:
        result = await wvp_service.stop_camera_play(device_id, channel_id)
        
        if result["success"]:
            return {
                "success": True,
                "data": result["data"],
                "message": result["message"]
            }
        else:
            raise HTTPException(
                status_code=400,
                detail=result["message"]
            )
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"停止播放失败: {e}")
        raise HTTPException(status_code=500, detail=f"停止播放失败: {str(e)}")


@router.post("/sync-cameras")
async def sync_cameras_from_wvp():
    """从Java后端WVP同步摄像头数据到本地数据库"""
    try:
        logger.info("🔄 开始从Java后端WVP同步摄像头数据...")
        
        result = await wvp_service.sync_cameras_from_wvp()
        
        if result["success"]:
            return {
                "success": True,
                "message": result["message"],
                "data": result["data"],
                "sync_time": datetime.now().isoformat()
            }
        else:
            raise HTTPException(
                status_code=500,
                detail=result["message"]
            )
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"同步摄像头数据失败: {e}")
        raise HTTPException(status_code=500, detail=f"同步失败: {str(e)}")


@router.post("/convert-to-cameras")
async def convert_wvp_to_cameras():
    """将Java后端WVP设备转换为本地摄像头"""
    try:
        logger.info("🚀 开始将Java后端WVP设备转换为摄像头...")
        
        camera_service = CameraService()
        db = get_database_manager()
        
        # 1. 从Java后端获取WVP摄像头数据
        wvp_result = await wvp_service.get_camera_list(page=1, count=1000, use_cache=False)
        
        if not wvp_result["success"]:
            raise HTTPException(
                status_code=404,
                detail=f"无法从Java后端获取WVP数据: {wvp_result['message']}"
            )
        
        cameras_data = wvp_result["data"]["list"]
        logger.info(f"从Java后端获取到 {len(cameras_data)} 个WVP摄像头")
        
        # 2. 转换为本地摄像头
        converted_count = 0
        skipped_count = 0
        error_count = 0
        
        for camera_data in cameras_data:
            device_id = camera_data["device_id"]
            channel_id = camera_data["channel_id"]
            
            try:
                # 检查是否已经有对应的摄像头
                existing_camera = db.get_camera_by_wvp_device(device_id, channel_id)
                if existing_camera:
                    # 检查现有摄像头是否缺少RTSP URL
                    current_rtsp = existing_camera.get('rtsp_url')
                    if not current_rtsp:
                        # 生成并更新RTSP URL
                        rtsp_url = f"rtsp://localhost:554/rtp/{device_id}_{channel_id}"
                        update_success = db.update_camera(existing_camera['id'], {'rtsp_url': rtsp_url})
                        if update_success:
                            logger.info(f"✅ 修复现有摄像头 {existing_camera['id']} 的RTSP URL: {rtsp_url}")
                            converted_count += 1  # 计入转换数量
                        else:
                            logger.error(f"❌ 修复摄像头 {existing_camera['id']} RTSP URL失败")
                            error_count += 1
                    else:
                        logger.info(f"设备 {device_id} 通道 {channel_id} 已有对应摄像头且RTSP URL正常，跳过")
                        skipped_count += 1
                    continue
                
                # 生成唯一的摄像头名称
                base_name = camera_data["name"]
                unique_name = base_name
                counter = 1
                
                while db.get_camera_by_name(unique_name):
                    unique_name = f"{base_name}_{counter}"
                    counter += 1
                
                # 生成正确的RTSP URL格式: rtsp://localhost:554/rtp/设备ID_通道ID
                rtsp_url = f"rtsp://localhost:554/rtp/{device_id}_{channel_id}"
                
                # 创建摄像头数据
                new_camera_data = {
                    'name': unique_name,
                    'wvp_device_id': device_id,
                    'wvp_channel_id': channel_id,
                    'location': camera_data.get("location", "未知位置"),
                    'longitude': float(camera_data.get("longitude", 0.0)),
                    'latitude': float(camera_data.get("latitude", 0.0)),
                    'description': f"从Java后端WVP设备 {device_id} 通道 {channel_id} 转换",
                    'ai_enabled': True,
                    'status': camera_data.get("status", "offline"),
                    'rtsp_url': rtsp_url
                }
                
                logger.info(f"生成RTSP URL: {rtsp_url} (设备: {device_id}, 通道: {channel_id})")
                logger.info(f"准备创建摄像头数据: {new_camera_data}")
                
                # 创建摄像头
                camera_id = await camera_service.create_camera(new_camera_data)
                if camera_id:
                    converted_count += 1
                    logger.info(f"✅ 成功转换 {device_id}/{channel_id} 为摄像头 {camera_id}")
                    
                    # 验证创建后的RTSP URL
                    created_camera = await camera_service.get_camera(str(camera_id))
                    if created_camera:
                        actual_rtsp = created_camera.get('rtsp_url')
                        logger.info(f"验证创建后RTSP URL: {actual_rtsp}")
                        if actual_rtsp != rtsp_url:
                            logger.error(f"⚠️ RTSP URL不匹配! 期望: {rtsp_url}, 实际: {actual_rtsp}")
                    else:
                        logger.error(f"⚠️ 无法获取创建后的摄像头数据")
                else:
                    logger.error(f"❌ 转换 {device_id}/{channel_id} 失败: 未返回摄像头ID")
                    error_count += 1
                    
            except Exception as e:
                logger.error(f"❌ 转换 {device_id}/{channel_id} 失败: {e}")
                error_count += 1
                continue
        
        # 3. 执行全面的RTSP URL修复（集成fix_rtsp_urls.py的功能）
        logger.info("🔧 执行全面的RTSP URL修复...")
        
        # 查找所有需要修复RTSP URL的摄像头
        fix_query = """
            SELECT id, name, wvp_device_id, wvp_channel_id, rtsp_url 
            FROM cameras 
            WHERE wvp_device_id IS NOT NULL 
            AND wvp_channel_id IS NOT NULL 
            AND (rtsp_url IS NULL OR rtsp_url = '')
        """
        
        cameras_to_fix = db.execute_query(fix_query)
        fixed_count = 0
        
        if cameras_to_fix:
            logger.info(f"发现 {len(cameras_to_fix)} 个需要修复RTSP URL的摄像头")
            
            for camera in cameras_to_fix:
                try:
                    camera_id = camera['id']
                    device_id = camera['wvp_device_id']
                    channel_id = camera['wvp_channel_id']
                    
                    # 生成正确的RTSP URL
                    rtsp_url = f"rtsp://localhost:554/rtp/{device_id}_{channel_id}"
                    
                    # 更新数据库
                    update_query = "UPDATE cameras SET rtsp_url = ? WHERE id = ?"
                    rows_affected = db.execute_update(update_query, (rtsp_url, camera_id))
                    
                    if rows_affected > 0:
                        logger.info(f"✅ 修复摄像头 {camera_id} ({camera['name']}) RTSP URL: {rtsp_url}")
                        fixed_count += 1
                    else:
                        logger.error(f"❌ 修复摄像头 {camera_id} 失败")
                        error_count += 1
                        
                except Exception as e:
                    logger.error(f"❌ 修复摄像头 {camera.get('id', 'unknown')} RTSP URL失败: {e}")
                    error_count += 1
        else:
            logger.info("所有WVP摄像头的RTSP URL都已正确设置")
        
        # 4. 验证最终结果
        total_cameras = db.execute_query("SELECT COUNT(*) as count FROM cameras")[0]['count']
        wvp_cameras = db.execute_query("SELECT COUNT(*) as count FROM cameras WHERE wvp_device_id IS NOT NULL")[0]['count']
        
        # 验证RTSP URL修复结果
        remaining_null_rtsp = db.execute_query("""
            SELECT COUNT(*) as count 
            FROM cameras 
            WHERE wvp_device_id IS NOT NULL 
            AND wvp_channel_id IS NOT NULL 
            AND (rtsp_url IS NULL OR rtsp_url = '')
        """)[0]['count']
        
        rtsp_success_rate = ((wvp_cameras - remaining_null_rtsp) / wvp_cameras * 100) if wvp_cameras > 0 else 100
        
        logger.info("🎉 WVP设备转换和RTSP修复完成!")
        logger.info(f"  Java后端WVP摄像头: {len(cameras_data)}")
        logger.info(f"  新建摄像头: {converted_count}")
        logger.info(f"  跳过摄像头: {skipped_count}")
        logger.info(f"  RTSP修复数量: {fixed_count}")
        logger.info(f"  错误数量: {error_count}")
        logger.info(f"  数据库总摄像头: {total_cameras}")
        logger.info(f"  WVP摄像头: {wvp_cameras}")
        logger.info(f"  RTSP成功率: {rtsp_success_rate:.1f}%")
        
        return {
            "success": True,
            "message": "Java后端WVP设备转换和RTSP修复完成",
            "source": "Java后端WVP服务",
            "wvp_cameras_found": len(cameras_data),
            "converted_cameras": converted_count,
            "skipped_cameras": skipped_count,
            "rtsp_fixed_count": fixed_count,
            "error_count": error_count,
            "total_cameras_in_db": total_cameras,
            "wvp_cameras_in_db": wvp_cameras,
            "rtsp_success_rate": rtsp_success_rate,
            "remaining_null_rtsp": remaining_null_rtsp,
            "conversion_time": datetime.now().isoformat()
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"WVP设备转换失败: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"WVP设备转换失败: {str(e)}")


@router.post("/sync-and-convert")
async def sync_and_convert_wvp():
    """一键从Java后端WVP同步并转换为摄像头"""
    try:
        logger.info("🚀 开始一键从Java后端WVP同步和转换...")
        
        # 1. 先同步数据
        sync_result = await sync_cameras_from_wvp()
        
        if not sync_result.get("success"):
            raise HTTPException(status_code=500, detail="数据同步失败")
        
        logger.info("✅ 数据同步完成，开始转换摄像头...")
        
        # 2. 再转换摄像头
        convert_result = await convert_wvp_to_cameras()
        
        if not convert_result.get("success"):
            raise HTTPException(status_code=500, detail="摄像头转换失败")
        
        logger.info("🎉 一键同步和转换完成!")
        
        # 提取RTSP修复信息
        rtsp_info = ""
        if convert_result.get("rtsp_fixed_count", 0) > 0:
            rtsp_info = f"，修复了 {convert_result['rtsp_fixed_count']} 个摄像头的RTSP URL"
        
        return {
            "success": True,
            "message": f"Java后端WVP数据同步和转换完成{rtsp_info}",
            "sync_result": sync_result,
            "convert_result": convert_result,
            "rtsp_success_rate": convert_result.get("rtsp_success_rate", 0),
            "total_time": datetime.now().isoformat()
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"一键同步和转换失败: {e}")
        raise HTTPException(status_code=500, detail=f"一键同步和转换失败: {str(e)}")


@router.get("/status")
async def get_wvp_status():
    """获取WVP服务状态"""
    try:
        # 检查Java后端连接
        connection_result = await wvp_service.test_wvp_connection()
        
        # 检查本地数据库
        db = get_database_manager()
        
        try:
            local_cameras = db.execute_query("SELECT COUNT(*) as count FROM cameras")[0]['count']
            wvp_cameras = db.execute_query("SELECT COUNT(*) as count FROM cameras WHERE wvp_device_id IS NOT NULL")[0]['count']
        except:
            local_cameras = wvp_cameras = 0
        
        return {
            "java_backend_wvp": {
                "connected": connection_result["success"],
                "server_url": connection_result.get("data", {}).get("server_url", ""),
                "total_devices": connection_result.get("data", {}).get("total_devices", 0),
                "error": connection_result.get("message", "") if not connection_result["success"] else None
            },
            "local_database": {
                "total_cameras": local_cameras,
                "wvp_cameras": wvp_cameras
            },
            "status_time": datetime.now().isoformat()
        }
        
    except Exception as e:
        logger.error(f"获取WVP状态失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取状态失败: {str(e)}")


@router.get("/devices")
async def get_wvp_devices(
    page: int = Query(1, ge=1, description="页码"),
    count: int = Query(50, ge=1, le=1000, description="每页数量")
):
    """获取WVP设备列表（从Java后端获取）"""
    try:
        # 通过摄像头列表获取设备信息
        cameras_result = await wvp_service.get_camera_list(page=page, count=count)
        
        if not cameras_result["success"]:
            raise HTTPException(
                status_code=404,
                detail=cameras_result["message"]
            )
        
        cameras = cameras_result["data"]["list"]
        
        # 按设备ID分组
        devices_map = {}
        for camera in cameras:
            device_id = camera["device_id"]
            if device_id not in devices_map:
                devices_map[device_id] = {
                    "device_id": device_id,
                    "device_name": camera["name"].split("-")[0] if "-" in camera["name"] else camera["name"],
                    "manufacturer": camera.get("manufacturer", ""),
                    "model": camera.get("model", ""),
                    "ip_address": camera.get("ip_address", ""),
                    "port": camera.get("port", 5060),
                    "status": camera.get("status", "offline"),
                    "channels": []
                }
            
            # 添加通道信息
            devices_map[device_id]["channels"].append({
                "channel_id": camera["channel_id"],
                "channel_name": camera["name"],
                "status": camera.get("status", "offline"),
                "location": camera.get("location", ""),
                "longitude": camera.get("longitude"),
                "latitude": camera.get("latitude")
            })
        
        devices = list(devices_map.values())
        
        return {
            "success": True,
            "data": {
                "devices": devices,
                "total": len(devices),
                "page": page,
                "count": count
            },
            "message": "从Java后端WVP获取设备列表成功"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取WVP设备列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取设备列表失败: {str(e)}")


@router.get("/devices/{device_id}/channels")
async def get_device_channels(device_id: str):
    """获取设备通道列表（从Java后端获取）"""
    try:
        # 通过摄像头列表获取该设备的通道
        cameras_result = await wvp_service.get_camera_list(page=1, count=1000)
        
        if not cameras_result["success"]:
            raise HTTPException(
                status_code=404,
                detail=cameras_result["message"]
            )
        
        cameras = cameras_result["data"]["list"]
        
        # 筛选该设备的通道
        device_channels = []
        for camera in cameras:
            if camera["device_id"] == device_id:
                device_channels.append({
                    "channel_id": camera["channel_id"],
                    "channel_name": camera["name"],
                    "status": camera.get("status", "offline"),
                    "location": camera.get("location", ""),
                    "longitude": camera.get("longitude"),
                    "latitude": camera.get("latitude"),
                    "channel_type": camera.get("channel_type", 0),
                    "has_audio": camera.get("has_audio", False),
                    "ptz_type": camera.get("ptz_type", 0)
                })
        
        if not device_channels:
            raise HTTPException(
                status_code=404,
                detail=f"设备 {device_id} 不存在或没有通道"
            )
        
        return {
            "success": True,
            "data": {
                "device_id": device_id,
                "channels": device_channels,
                "total": len(device_channels)
            },
            "message": f"获取设备 {device_id} 通道列表成功"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取设备通道列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取通道列表失败: {str(e)}")